# tcm11
from flask import Flask, jsonify, redirect, request, render_template,make_response, session, url_for ,flash
import requests
app = Flask(__name__)

students = [
    {'id': 1, 'name': '张三', 'gender': '男', 'age': 18, 'id_card': '123456789', 'phone': '12345678901', 'address': '北京'},
    {'id': 2, 'name': '李四', 'gender': '男', 'age': 19, 'id_card': '123456780', 'phone': '12345678902', 'address': '上海'},
    {'id': 3, 'name': '王五', 'gender': '女', 'age': 20, 'id_card': '123456781', 'phone': '12345678903', 'address': '广州'}
]

courses = [
    {'id': 123, 'course': '数学', 'teacher': '王老师','stime': 2, 'week': '星期一', 'address': '101教室'}
]

scores = [
    # 示例数据
    {'student_id': 1, 'name':'张三', 'course_id': '123','course':'数学', 'point': 90},
    # ...
]

users = {
    "user1": "password1",
    "user2": "password2"
}

# Login route
#from flask import Flask, request, render_template, redirect, url_for, session, flash

#app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 用于加密会话

# 假设这是您的用户数据库（在实际应用中，这应该是一个真实的数据库）


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        if username in users and users[username] == password:
            session['username'] = username  # 登录成功，创建会话
            return redirect(url_for('index'))  # 重定向到主页
        else:
            flash('用户名或密码错误')  # 显示错误消息
    return render_template('login.html')  # 渲染登录表单



# Logout route
@app.route('/logout')
def logout():
    session.pop('username', None)  # 删除会话中的用户名
    return redirect(url_for('login'))  # 重定向到登录页面


# Register route
@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        if username in users:
            flash('用户名已存在')  # 显示错误消息
        else:
            users[username] = password  # 添加新用户
            return redirect(url_for('login'))  # 重定向到登录页面
    return render_template('register.html')  # 渲染注册表单


@app.route('/change-password', methods=['GET', 'POST'])
def change_password():
    if 'username' not in session:  # 确保用户已登录
        return redirect(url_for('login'))

    if request.method == 'POST':
        old_password = request.form['old_password']
        new_password = request.form['new_password']
        username = session['username']

        if username in users and users[username] == old_password:
            users[username] = new_password  # 更新密码
            flash('密码已更改')
            return redirect(url_for('index'))  # 重定向到主页
        else:
            flash('旧密码错误')
    return render_template('change_password.html')  # 渲染更改密码表单



@app.route('/') # 获取学生信息页面
def index():
    return render_template('index.html')

@app.route('/score') # 获取成绩信息页面
def score():
    return render_template('score.html')

@app.route('/course') # 获取课程信息页面
def course():
    return render_template('course.html')

@app.route('/addStu',methods=['post']) # 添加学生信息页面
def addStu():
    stu = eval(request.data.decode('utf-8'))

    stu['id'] = int(stu['id'])
    students.append(stu)
    return 'haha'

@app.route('/courses',methods=['post']) # 添加课程信息页面
def addCourse():
    course = eval(request.data.decode('utf-8'))

    course['id'] = int(course['id'])
    courses.append(course)
    return 'haha'

@app.route('/scores',methods=['post']) # 添加成绩信息页面
def addScore():
    score = eval(request.data.decode('utf-8'))

    score['id'] = int(score['id'])
    scores.append(score)
    return 'haha'


@app.route('/delStu/<int:student_id>', methods=['DELETE'])
def delete_student(student_id):
    global students, scores
    student_to_delete = next((student for student in students if student['id'] == student_id), None)
    
    if student_to_delete:
        print(f"Deleting student: {student_to_delete}")  # Debug print
        students.remove(student_to_delete)
        # 删除该学生的所有成绩
        scores = [score for score in scores if score.get('student_id') != student_id]
        print(f"Remaining scores after deletion: {score}")  # Debug print
        
        return jsonify({'message': 'Student and associated scores deleted successfully'}), 200
    else:
        return jsonify({'message': 'Student not found'}), 404


@app.route('/delCourse/<int:course_id>', methods=['DELETE'])
def delete_course(course_id):
    global courses, scores
    str_course_id = str(course_id)  # 将整数类型的课程 ID 转换为字符串类型

    course_to_delete = next((course for course in courses if course['id'] == course_id), None)
    
    if course_to_delete:
        courses.remove(course_to_delete)
        # 删除与该课程相关的所有成绩
        scores = [score for score in scores if score.get('course_id') != str_course_id]
        
        return jsonify({'message': 'Course and associated scores deleted successfully'}), 200
    else:
        return jsonify({'message': 'Course not found'}), 404



@app.route('/scores/<int:score_id>', methods=['DELETE'])
def delete_score(score_id):
    global scores
    # 查找并删除记录
    score_to_delete = next((score for score in scores if score['id'] == score_id), None)
    if score_to_delete:
        scores.remove(score_to_delete)
        return jsonify({'message': 'Score deleted successfully'}), 200
    else:
        return jsonify({'error': 'Score not found'}), 404


    
@app.route('/editStu/<int:student_id>', methods=['PUT'])
def edit_student_by_id(student_id):
    # 找到要更新的学生记录
    student_to_update = next((student for student in students if student['id'] == student_id), None)
    if student_to_update is None:
        return jsonify({'message': 'Student not found'}), 404

    stu = request.get_json()

    student_to_update.update(stu)

    return jsonify({'message': 'Student edited successfully'}), 200

@app.route('/editCours/<int:course_id>', methods=['PUT'])
def edit_course_by_id(course_id):
    # 找到要更新的课程记录
    course_to_update = next((course for course in courses if course['id'] == course_id), None)
    if course_to_update is None:
        return jsonify({'message': 'Course not found'}), 404

    course_data = request.get_json()

    course_to_update.update(course_data)

    return jsonify({'message': 'Course edited successfully'}), 200

@app.route('/editScore/<int:score_id>', methods=['PUT'])
def edit_score_by_id(score_id):
    # 找到要更新的成绩记录
    score_to_update = next((score for score in scores if score['id'] == score_id), None)
    if score_to_update is None:
        return jsonify({'message': 'Score not found'}), 404

    score_data = request.get_json()

    score_to_update.update(score_data)

    return jsonify({'message': 'Score edited successfully'}), 200


@app.route('/courses') # 获取课程信息页面
def getCourses():
    return jsonify(courses)

@app.route('/scores') # 获取成绩信息页面
def getScores():
    return jsonify(scores)

@app.route('/students') # 获取学生信息页面
def getStudents():
    return jsonify(students)



if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0',port=80)


